<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ form.id?'编辑':'新增'}}矿难奖池</span>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-form-item>
            <el-button type="primary" @click="WXonSubmit">立即创建</el-button>
            <el-button @click="WXCancel">取消</el-button>
          </el-form-item>
          <el-form-item label="矿难名称" prop="name">
            <el-input v-model="form.name" style="width:360px" placeholder="请输入盲盒名称"></el-input>
          </el-form-item>

          <el-row :gutter="20">
            <el-col :span="24">
              <el-button size="small" type="primary" round @click="addRewards(1)">添加1级奖品</el-button>
              <el-form-item label="1级石头数量" prop="num1">
                <el-input-number
                  :min="1"
                  :max="10"
                  v-model="form.num1"
                  style="width:360px"
                  placeholder="请输入石头数量"
                ></el-input-number>
              </el-form-item>
              <feedbackTable
                :goods_data="form.goods_data1"
                :ruleoptions="ruleoptions"
                :level="1"
                @updata="updata1"
              ></feedbackTable>
            </el-col>
            <el-col :span="24">
              <el-button size="small" type="primary" round @click="addRewards(2)">添加2级奖品</el-button>
              <el-form-item label="2级石头数量" prop="num2">
                <el-input-number
                  :min="1"
                  :max="10"
                  v-model="form.num2"
                  style="width:360px"
                  placeholder="请输入石头数量"
                ></el-input-number>
              </el-form-item>
              <feedbackTable
                :goods_data="form.goods_data2"
                :ruleoptions="ruleoptions"
                :level="2"
                @updata="updata2"
              ></feedbackTable>
            </el-col>
            <el-col :span="24">
              <el-button size="small" type="primary" round @click="addRewards(3)">添加3级奖品</el-button>
              <el-form-item label="3级石头数量" prop="num3">
                <el-input-number
                  :min="1"
                  :max="10"
                  v-model="form.num3"
                  style="width:360px"
                  placeholder="请输入石头数量"
                ></el-input-number>
              </el-form-item>
              <feedbackTable
                :goods_data="form.goods_data3"
                :ruleoptions="ruleoptions"
                :level="3"
                @updata="updata3"
              ></feedbackTable>
            </el-col>
          </el-row>
        </el-row>
      </el-form>
    </el-card>

    <!-- 抽屉 -->
    <el-drawer
      :title="`添加${ addState} 级奖品`"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
    >
      <el-form ref="query" :model="query" label-width="80px">
        <el-form-item label="奖品名称">
          <el-input v-model="query.keywords" placeholder="请输入奖品名称"></el-input>
        </el-form-item>
        <el-form-item label="价格区间">
          <el-input v-model="query.lowPrice" style="width:50px" placeholder="低"></el-input>-
          <el-input v-model="query.heightPrice" style="width:50px" placeholder="高"></el-input>
        </el-form-item>
        <el-form-item label="奖品分类">
          <el-cascader
            @focus="getBoxRewardTypeList"
            v-model="query.class_id"
            :options="queryOptioins"
            :props="{ checkStrictly: true,value:'id',label:'class_name' }"
            placeholder="请选择奖品分类"
            clearable
            :loading="queryLoading"
          ></el-cascader>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryAsk">筛选</el-button>
          <el-button @click="queryReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        @sort-change="sortChange"
        ref="multipleTable"
        :header-cell-style="{background:'#eee'}"
        :data="boxRewardData"
        v-loading="loading"
        border
        style="width: 100%;margin-bottom: 20px;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column align="center" prop="id" label="ID"></el-table-column>
        <el-table-column align="center" prop="goods_name" label="奖品名称"></el-table-column>
        <el-table-column align="center" label="奖品图片">
          <template slot-scope="scope">
            <el-popover placement="top-start" title trigger="hover">
              <img :src="scope.row.img" alt style="max-width:150px" />
              <el-avatar
                slot="reference"
                shape="square"
                :size="50"
                fit="scale-down"
                :src="scope.row.img"
              ></el-avatar>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="class_name" label="分类"></el-table-column>
        <el-table-column align="center" prop="y_price" label="成本"></el-table-column>
        <el-table-column align="center" prop="price" label="价格" sortable="custom"></el-table-column>
        <el-table-column align="center" prop="address" label="预售/现货">
          <template slot-scope="scope">
            <div v-if="scope.row.type==1">预售</div>
            <div v-if="scope.row.type==2">现货</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="address" label="是否参与合成材料">
          <template slot-scope="scope">
            <div v-if="scope.row.is_compound==1">可以</div>
            <div v-if="scope.row.is_compound==0">不可以</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="compound_price" label="合成数值"></el-table-column>
      </el-table>
      <div style="text-align:right">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="currentPage"
          :total="total"
          @current-change="currentChange"
        ></el-pagination>
      </div>

      <div style="margin-top:20px;float:right">
        <el-button type="primary" @click="onSubmit">确定</el-button>
        <el-button @click="subCancel">取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { upload } from '@/api/system'
import { boxRewardList, boxRewardTypeList } from '@/api/boxreward'
import { categoryList } from '@/api/product'
import { addWXBox, boxinfo, editWXBox } from '@/api/blindbox'
import { add, edit, detail } from '@/api/feedback'
import { rewardList } from '@/api/system'
import { parseTime } from '@/utils/index'
import feedbackTable from './components/feedbackTable'
export default {
  name: 'addFeedback',
  components: { feedbackTable },
  data() {
    return {
      // 分页数据
      total: 0,
      currentPage: 1,
      pageSize: 10,
      //query
      query: {
        keywords: '',
        class_id: '0',
        lowPrice: '',
        heightPrice: '',
        order_by: ''
      },
      boxRewardData: [],
      form: {
        level: 1,
        name: '',
        num1: 4,
        num2: 3,
        num3: 2,
        goods_data1: [],
        goods_data2: [],
        goods_data3: []
      },
      rules: {
        name: [{ required: true, message: '请输入盲盒名称', trigger: 'blur' }],
        num1: [{ required: true, message: '请输入', trigger: 'blur' }],
        num2: [{ required: true, message: '请输入', trigger: 'blur' }],
        num3: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      // 编辑抽屉
      drawer: false,
      loading: false,
      priceArr: [],
      queryLoading: false,
      queryOptioins: [],
      //添加奖品列表
      selectArr: [],
      ruleoptions: [],
      classId: '0',
      addState: '1'
    }
  },
  mounted() {
    this.getrule()
    if (this.$route.query.id) {
      this.getInfo()
    }
  },
  activated() {
    this.getrule()
    if (this.$route.query.id) {
      this.getInfo()
    }
  },
  methods: {
    updata1(e) {
      console.log(e)
      this.form.goods_data1 = e.map((item) => {
        return Object.assign({}, item, { level: 1 })
      })
      console.log(this.form.goods_data1)
    },
    updata2(e) {
      this.form.goods_data2 = e
      this.form.goods_data1 = e.map((item) => {
        return Object.assign({}, item, { level: 2 })
      })
    },
    updata3(e) {
      this.form.goods_data3 = e
      this.form.goods_data1 = e.map((item) => {
        return Object.assign({}, item, { level: 3 })
      })
    },
    // 获取分类
    async getrule() {
      const res = await rewardList()
      this.ruleoptions = res.data
    },
    // 获取详细信息
    async getInfo() {
      const res = await detail({ mine_id: this.$route.query.id })
      console.log(res, '2132313231')
      this.form = Object.assign({}, res.data, {
        goods_data1: res.data.goods_data[1],
        goods_data2: res.data.goods_data[2],
        goods_data3: res.data.goods_data[3]
      })
    },
    // 去除小数最后的0
    removeTrailingZeros(num) {
      const str = num.toString()
      return str.indexOf('.') !== -1 ? str.replace(/\.?0*$/, '') : str
    },
    canSubmit(goods_data, level) {
      let bool = true
      let probability = 0
      goods_data.forEach((item) => {
        probability = Number(
          (probability += Number(item.probability)).toFixed(3)
        )
      })
      if (probability != 100) {
        this.$message.error(
          `奖池${level}中所有中奖概率不等于百分百！` + probability
        )
        bool = false
        return false
      }
      // 检查表中数据有无漏填
      for (let i = 0; i < goods_data.length; i++) {
        if (!goods_data[i].rule_id) {
          this.$message.error(`奖池${level}中请选择中奖名称！`)
          bool = false
          return false
        }
      }
      return true
    },
    WXonSubmit() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          if (!this.canSubmit(this.form.goods_data1, 1)) {
            console.log(1)
            return false
          }
          if (!this.canSubmit(this.form.goods_data2, 2)) {
            console.log(1)

            return false
          }
          if (!this.canSubmit(this.form.goods_data3, 3)) {
            console.log(1)

            return false
          }
          if (!this.form.id) {
            console.log(1)

            const pushForm = Object.assign({}, this.form)
            console.log(pushForm)

            const res = await add({ ...pushForm })
            if (res.st == 1) {
              this.$message({
                message: '添加成功',
                type: 'success'
              })

              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch('tagsView/delView', this.$route)
              //返回上一个tab页面 返回上一步路由，
              this.$router.go(-1)
            } else {
              console.log(res)
              this.$message.error(res.msg)
            }
          } else if (this.form.id) {
            const pushForm = Object.assign({}, this.form)
            console.log(pushForm)
            const res = await edit({ ...pushForm })
            if (res.st == 1) {
              this.$message({
                message: '编辑成功',
                type: 'success'
              })

              // 调用全局挂载的方法,关闭当前标签页
              this.$store.dispatch('tagsView/delView', this.$route)
              //返回上一个tab页面 返回上一步路由，
              this.$router.go(-1)
            } else {
              console.log(res)
              this.$message.error(res.msg)
            }
          }
        }
      })
    },
    WXCancel() {
      // 调用全局挂载的方法,关闭当前标签页
      this.$store.dispatch('tagsView/delView', this.$route)
      //返回上一个tab页面 返回上一步路由，
      this.$router.go(-1)
    },
    //抽屉
    handleClose(done) {
      this.drawer = false
      done()
    },
    subCancel() {
      this.drawer = false
    },
    //分页改变
    async currentChange(current) {
      this.currentPage = current
      await this.getBoxRewardList()
      const select = []
      let goodsData = []
      if (this.addState == 1) {
        goodsData = this.form.goods_data1
      }
      if (this.addState == 2) {
        goodsData = this.form.goods_data2
      }
      if (this.addState == 3) {
        goodsData = this.form.goods_data3
      }
      if (goodsData.length) {
        goodsData.forEach((good) => {
          this.boxRewardData.forEach((item) => {
            if (good.goods_id == item.id) {
              select.push(item)
            }
          })
        })
      }
      this.toggleSelection(select)
    },
    // 添加奖品
    async addRewards(e) {
      this.addState = e
      this.drawer = true
      await this.getBoxRewardList()
      const select = []
      let goodsData = []
      if (this.addState == 1) {
        goodsData = this.form.goods_data1
      }
      if (this.addState == 2) {
        goodsData = this.form.goods_data2
      }
      if (this.addState == 3) {
        goodsData = this.form.goods_data3
      }
      if (goodsData) {
        goodsData.forEach((good) => {
          this.boxRewardData.forEach((item) => {
            if (good.goods_id == item.id) {
              select.push(item)
            }
          })
        })
      }
      this.toggleSelection(select)
      this.selectArr = goodsData
    },
    //获取奖品列表
    async getBoxRewardList() {
      this.loading = true
      const res = await boxRewardList({
        page: this.currentPage,
        limit: this.pageSize,
        class_id: this.classId,
        price: this.priceArr,
        keywords: this.query.keywords,
        order_by: this.query.order_by
      })
      this.loading = false
      console.log(res)
      this.total = res.count
      this.boxRewardData = res.data
    },
    //获取奖品分类列表
    async getBoxRewardTypeList() {
      this.queryLoading = true
      const res = await categoryList({
        page: '1',
        limit: '999',
        keywords: ''
      })
      this.queryLoading = false
      console.log(res)
      this.queryOptioins = res.data
    },
    // 搜索列表
    queryAsk() {
      // 不可以一个有值一个没值
      if (!this.query.lowPrice && !this.query.heightPrice) {
        console.log(this.query)
        this.priceArr = []
        this.classId = this.query.class_id[this.query.class_id.length - 1]
        this.currentPage = 1
        this.getBoxRewardList()
      } else if (this.query.lowPrice && this.query.heightPrice) {
        this.priceArr = [this.query.lowPrice, this.query.heightPrice]
        console.log(this.query)
        this.classId = this.query.class_id[this.query.class_id.length - 1]
        this.currentPage = 1
        this.getBoxRewardList()
      } else if (!this.query.lowPrice || !this.query.heightPrice) {
        this.$message.error('请输入价格区间')
      }
    },
    queryReset() {
      this.resetForm('query')
      this.total = 0
      this.currentPage = 1
      this.pageSize = 10
      this.query.keywords = ''
      this.query.type = '0'
      this.query.lowPrice = ''
      this.query.heightPrice = ''
      this.query.order_by = ''
      this.query.class_id = '0'
      this.classId = '0'
      this.getBoxRewardList()
    },
    // 选择奖品
    toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },

    handleSelectionChange(val) {
      this.selectArr = []
      //已经有的不添加
      const aIds = new Set(this.selectArr.map((item) => item.id))
      val.forEach((item) => {
        if (!aIds.has(item.id)) {
          this.selectArr.push(item)
        }
      })
    },
    onSubmit() {
      console.log(this.addState, 'this.addStatethis.addStatethis.addState')
      let goodsData = []
      if (this.addState == 1) {
        goodsData = this.form.goods_data1
      }
      if (this.addState == 2) {
        goodsData = this.form.goods_data2
      }
      if (this.addState == 3) {
        goodsData = this.form.goods_data3
      }
      const aIds = new Set(goodsData.map((item) => item.goods_id))
      this.selectArr.forEach((item) => {
        if (!aIds.has(item.id)) {
          const dx = {
            goods_id: item.id,
            rule_id: '',
            sort: '',
            num: '0',
            win_type: '-1',
            stage_start: '0',
            stage_end: '0',
            img: item.img,
            goods_name: item.goods_name,
            price: item.price,
            y_price: item.y_price,
            clevel: item.clevel,
            id: '0'
          }
          goodsData.unshift(dx)
        }
      })
      goodsData.sort((a, b) => b.price - a.price)
      goodsData.forEach((item, index) => {
        console.log(index)
        item.sort = goodsData.length - (index + 1)
      })
      if (this.addState == 1) {
        console.log(1111111)
        this.form.goods_data1 = goodsData
      }
      if (this.addState == 2) {
        console.log(222222)

        this.form.goods_data2 = goodsData
      }
      if (this.addState == 3) {
        console.log(3333333)

        this.form.goods_data3 = goodsData
      }
      this.drawer = false
    },
    async getrule() {
      const res = await rewardList({
        page: '1',
        limit: '999',
        keywords: '',
        type: '2'
      })
      this.ruleoptions = res.data
    },

    // 排序
    sortChange({ column, prop, order }) {
      if (order == 'descending') {
        this.query.order_by = prop + ',' + 'desc'
        this.getBoxRewardList()
      } else if (order == 'ascending') {
        this.query.order_by = prop + ',' + 'asc'
        this.getBoxRewardList()
      }
    },

    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: '';
}
.clearfix:after {
  clear: both;
}
.search {
  display: flex;
  align-items: center;
}
::v-deep .el-drawer.rtl {
  width: 650px !important;
  overflow: auto;
  .el-form {
    display: flex;
    flex-wrap: wrap;
  }
}
::v-deep .el-textarea__inner {
  width: 360px !important;
}
::v-deep .el-drawer.rtl {
  padding-bottom: 20px;
  width: 800px !important;
  overflow: auto;
}
// 上传图片
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 158px;
  height: 158px;
  line-height: 158px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>